package com.llyb.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.llyb.annotation.MyCacheAnnotation;
import com.llyb.exception.BusinessException;
import com.llyb.mapper.UserMapper;
import com.llyb.service.UserService;
import com.llyb.entities.User;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.io.Serializable;

/**
* @author liyb
* @description 针对表【t_user(用户表)】的数据库操作Service实现
* @createDate 2025-07-30 23:45:53
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService {

    private final static String USER_PREFIX = "user:";

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Autowired
    private UserMapper userMapper;

    @Override
    public boolean save(User entity) {

        boolean save = super.save(entity);

        if (save) {
            User user = userMapper.selectById(entity.getId());

            String key = USER_PREFIX + entity.getId();
            redisTemplate.opsForValue().set(key,user);

        }

        return save;
    }

    /*@Override
    public User getById(Serializable id) {

        String key = USER_PREFIX + id;
        User user = (User)redisTemplate.opsForValue().get(key);

        if (!ObjectUtils.isEmpty(user)) {
            return user;
        }

        User result = userMapper.selectById(id);

        if (!ObjectUtils.isEmpty(result)) {
            redisTemplate.opsForValue().set(key,result);
        }
        return result;
    }*/

    @Override
    @MyCacheAnnotation(keyPrefix = "user",matchMessage = "#id")
    public User getById(Serializable id) {
        User result = userMapper.selectById(id);
        return result;
    }
}




